
<?php

class Address extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    function getCoordinates($address) {

        $address = str_replace(" ", "+", $address); // replace all the white space with "+" sign to match with google search pattern
        $url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=$address";
        $response = file_get_contents($url);
        $json = json_decode($response, TRUE); //generate array object from the response from the web
        $coordinate['lat'] = $json['results'][0]['geometry']['location']['lat'];
        $coordinate['long'] = $json['results'][0]['geometry']['location']['lng'];
        return $coordinate;
        //($json['results'][0]['geometry']['location']['lat'] . "," . $json['results'][0]['geometry']['location']['lng']);
    }

    function ottieniLatLong($indirizzo) {
        if (!is_string($indirizzo))
            die("Tutti gli indirizzi devono essere inseriti come stringa");
        $_url = sprintf('http://maps.google.com/maps?output=js&q=%s', rawurlencode($indirizzo));
        $_result = false;
        if ($_result = file_get_contents($_url)) {
            if (strpos($_result, 'errortips') > 1 || strpos($_result, 'Did you mean:') !== false)
                return false;
            preg_match('!center:\s*{lat:\s*(?\d+\.\d+),lng:\s*(?\d+\.\d+)}!U', $_result, $_match);
            $_coord['lat'] = $_match[1];
            $_coord['long'] = $_match[2];
        } return $_coord;
    }

    function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2, $unit = 'Mi') {
        $theta = $longitude1 - $longitude2;
        $distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
        $distance = acos($distance);
        $distance = rad2deg($distance);
        $distance = $distance * 60 * 1.1515;
        switch ($unit) {
            case 'Mi': break;
            case 'Km' : $distance = $distance * 1.609344;
        }
        return (round($distance, 2));
    }

    function getPetSitterNearer($_coord, $distance, $service = NULL) {
        if($service == NULL){
            $sql = sprintf("SELECT `nearUser`.`Id`,`nearUser`.`Nome` , `nearUser`.`Cognome` ,
                                `nearUser`.`DataDiNascita` , `nearUser`.`Citta` , `nearUser`.`Indirizzo` ,
                                `fotopet‏sitter`.`Percorso` AS 'path_profile',`fotopet‏sitter`.`Nome` AS 'alt_profile',
                                `nearUser`.`lat` ,`nearUser`.`long`,
                                `curriculum`.`TitoloAnnuncio` , `curriculum`.`DescrizioneAnnuncio`,
                                `curriculum`.`Certificazioni` , `curriculum`.`Specializzazioni`,
                                `esperienza‏`.`Nome` AS 'Esperienza' , `esperienza‏`.`Descrizione`,
                                `costi`.`CostoGiornaliero`, `costi`.`CostoOrario`, `costi`.`CostoPetAggiuntivo`
                    FROM
                    (SELECT *,
                                p.distance_unit
                                         * DEGREES(ACOS(COS(RADIANS(p.latpoint))
                                         * COS(RADIANS(z.`lat`))
                                         * COS(RADIANS(p.longpoint) - RADIANS(z.`long`))
                                         + SIN(RADIANS(p.latpoint))
                                         * SIN(RADIANS(z.`long`)))) AS distance_in_km
                          FROM `utente` AS z
                          JOIN (   /* these are the query parameters */
                                SELECT  " . $_coord['lat'] . "  AS latpoint, " . $_coord['long'] . " AS longpoint,
                                        " . $distance . " AS radius,      111.045 AS distance_unit
                            ) AS p ON 1=1
                          WHERE z.`lat`
                             BETWEEN p.latpoint  - (p.radius / p.distance_unit)
                                 AND p.latpoint  + (p.radius / p.distance_unit)
                            AND z.`long`
                             BETWEEN p.longpoint - (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
                                 AND p.longpoint + (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
                          ORDER BY distance_in_km) as `nearUser`, `utentepetsitter` , `curriculum` , `esperienza‏`, `costi`,`fotopet‏sitter`
                     WHERE `nearUser`.`FKFoto` = `fotopet‏sitter`.`Id`
                     AND `nearUser`.`FKUtentePetSitter` = `utentepetsitter`.`Id`
                     AND `curriculum`.`Id` = `utentepetsitter`.`FKCurriculum`
                     AND `esperienza‏`.`Id` = `curriculum`.`FKEsperienza`
                     AND `costi`.`Id` = `utentepetsitter`.`FKCosti`");
        }elseif($service == 3){
            $sql = sprintf("SELECT `nearUser`.`Id`,`nearUser`.`Nome` , `nearUser`.`Cognome` ,
                                `nearUser`.`DataDiNascita` , `nearUser`.`Citta` , `nearUser`.`Indirizzo` ,
                                `fotopet‏sitter`.`Percorso` AS 'path_profile',`fotopet‏sitter`.`Nome` AS 'alt_profile',
                                `nearUser`.`lat` ,`nearUser`.`long`,
                                `curriculum`.`TitoloAnnuncio` , `curriculum`.`DescrizioneAnnuncio`,
                                `curriculum`.`Certificazioni` , `curriculum`.`Specializzazioni`,
                                `esperienza‏`.`Nome` AS 'Esperienza' , `esperienza‏`.`Descrizione`,
                                `costi`.`CostoGiornaliero`, `costi`.`CostoOrario`, `costi`.`CostoPetAggiuntivo`
                    FROM
                    (SELECT *,
                                p.distance_unit
                                         * DEGREES(ACOS(COS(RADIANS(p.latpoint))
                                         * COS(RADIANS(z.`lat`))
                                         * COS(RADIANS(p.longpoint) - RADIANS(z.`long`))
                                         + SIN(RADIANS(p.latpoint))
                                         * SIN(RADIANS(z.`long`)))) AS distance_in_km
                          FROM `utente` AS z
                          JOIN (   /* these are the query parameters */
                                SELECT  " . $_coord['lat'] . "  AS latpoint, " . $_coord['long'] . " AS longpoint,
                                        " . $distance . " AS radius,      111.045 AS distance_unit
                            ) AS p ON 1=1
                          WHERE z.`lat`
                             BETWEEN p.latpoint  - (p.radius / p.distance_unit)
                                 AND p.latpoint  + (p.radius / p.distance_unit)
                            AND z.`long`
                             BETWEEN p.longpoint - (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
                                 AND p.longpoint + (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
                          ORDER BY distance_in_km) as `nearUser`, `utentepetsitter` , `curriculum` , `esperienza‏`, `costi`,`fotopet‏sitter`
                     WHERE `nearUser`.`FKFoto` = `fotopet‏sitter`.`Id`
                     AND `nearUser`.`FKUtentePetSitter` = `utentepetsitter`.`Id`
                     AND `curriculum`.`Id` = `utentepetsitter`.`FKCurriculum`
                     AND `esperienza‏`.`Id` = `curriculum`.`FKEsperienza`
                     AND `costi`.`Id` = `utentepetsitter`.`FKCosti`
                     AND `utentepetsitter`.`FKCasa` != ''");
        }else{
            $sql = sprintf("SELECT `nearUser`.`Id`,`nearUser`.`Nome` , `nearUser`.`Cognome` ,
                                `nearUser`.`DataDiNascita` , `nearUser`.`Citta` , `nearUser`.`Indirizzo` ,
                                `fotopet‏sitter`.`Percorso` AS 'path_profile',`fotopet‏sitter`.`Nome` AS 'alt_profile',
                                `nearUser`.`lat` ,`nearUser`.`long`
                    FROM
                    (SELECT *,
                                p.distance_unit
                                         * DEGREES(ACOS(COS(RADIANS(p.latpoint))
                                         * COS(RADIANS(z.`lat`))
                                         * COS(RADIANS(p.longpoint) - RADIANS(z.`long`))
                                         + SIN(RADIANS(p.latpoint))
                                         * SIN(RADIANS(z.`long`)))) AS distance_in_km
                          FROM `utente` AS z
                          JOIN (   /* these are the query parameters */
                                SELECT  " . $_coord['lat'] . "  AS latpoint, " . $_coord['long'] . " AS longpoint,
                                        " . $distance . " AS radius,      111.045 AS distance_unit
                            ) AS p ON 1=1
                          WHERE z.`lat`
                             BETWEEN p.latpoint  - (p.radius / p.distance_unit)
                                 AND p.latpoint  + (p.radius / p.distance_unit)
                            AND z.`long`
                             BETWEEN p.longpoint - (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
                                 AND p.longpoint + (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
                          ORDER BY distance_in_km) as `nearUser`, `utentepet`,`fotopet‏sitter`
                     WHERE `nearUser`.`FKFoto` = `fotopet‏sitter`.`Id`
                     AND `nearUser`.`FKUtentePet` = `utentepet`.`Id`");
        }
        
        
        $query = $this->db->query($sql);
        $response = array();
        $i = 0;
        foreach ($query->result_array() as $row) {
            $response[$i] = $row;
            $i++;
        }


        return $response;
    }

    public function getVeterinariNear($_coord, $distance) {
        $sql = sprintf(" SELECT *,
                                p.distance_unit
                                         * DEGREES(ACOS(COS(RADIANS(p.latpoint))
                                         * COS(RADIANS(z.`lat`))
                                         * COS(RADIANS(p.longpoint) - RADIANS(z.`long`))
                                         + SIN(RADIANS(p.latpoint))
                                         * SIN(RADIANS(z.`long`)))) AS distance_in_km
                          FROM `veterinari` AS z
                          JOIN (   /* these are the query parameters */
                                SELECT  " . $_coord['lat'] . "  AS latpoint, " . $_coord['long'] . " AS longpoint,
                                        " . $distance . " AS radius,      111.045 AS distance_unit
                            ) AS p ON 1=1
                          WHERE z.`lat`
                             BETWEEN p.latpoint  - (p.radius / p.distance_unit)
                                 AND p.latpoint  + (p.radius / p.distance_unit)
                            AND z.`long`
                             BETWEEN p.longpoint - (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
                                 AND p.longpoint + (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
                          ORDER BY distance_in_km
                          LIMIT 15");

        $query = $this->db->query($sql);
        $response = array();
        $i = 0;
        foreach ($query->result_array() as $row) {
            $response[$i] = $row;
            $i++;
        }


        return $response;
    }

}
